<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card shadow="hover">
          <div style="height: 300px;">
            <div slot="header" class="clearfix" style="margin-bottom: 10px;">
              <span>订单地区</span>
            </div>
            <div v-for="item in this.address" :key="item.address">
              {{ item.address
              }}<el-progress
                :percentage="item.precent"
                color="#42b983"
              ></el-progress>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover">
          <schart
            ref="line"
            class="schart"
            canvasId="line"
            :data="data"
            type="line"
            :options="options2"
          ></schart>
        </el-card>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card shadow="hover">
          <div id="pieChart" style="width:100%;height:300px;"></div>
        </el-card>
      </el-col>
      <!-- <el-col :span="12">
        <el-card shadow="hover">
          <schart
            ref="bar"
            class="schart"
            canvasId="bar"
            :data="data"
            type="bar"
            :options="options"
          ></schart>
        </el-card>
      </el-col> -->
    </el-row>
  </div>
</template>

<script>
import Schart from "vue-schart";
import echarts from "echarts";
import bus from "../common/bus";
import { getOrderList } from "../../api/api";
export default {
  name: "dashboard",
  data() {
    return {
      name: localStorage.getItem("ms_username"),
      Echarts: null,
      address: [],
      data: [],
      // options: {
      //   title: "最近七天每天的用户访问量",
      //   showValue: false,
      //   fillColor: "rgb(45, 140, 240)",
      //   bottomPadding: 30,
      //   topPadding: 30
      // },
      options2: {
        title: "各月的销售金额",
        fillColor: "#FC6FA1",
        axisColor: "#008ACD",
        contentColor: "#EEEEEE",
        bgColor: "#F5F8FD",
        bottomPadding: 30,
        topPadding: 30
      },
      option3: {
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b}: {c} ({d}%)"
        },
        // 饼状图左侧
        legend: {
          orient: "vertical",
          x: "left",
          data: []
        },
        // 饼状图内部
        series: [
          {
            name: "支付方式",
            type: "pie",
            selectedMode: "single",
            radius: [0, "30%"],

            label: {
              normal: {
                position: "inner"
              }
            },
            labelLine: {
              normal: {
                show: false
              }
            },
            data: []
          },
          // 饼状图外围
          {
            name: "支付方式",
            type: "pie",
            radius: ["40%", "55%"],
            label: {
              normal: {
                show: false,
                formatter: "{a|{a}}{abg|}\n{hr|}\n  {b|{b}：}{c}  {per|{d}%}  ",
                backgroundColor: "#eee",
                borderColor: "#aaa",
                borderWidth: 1,
                borderRadius: 4,
                rich: {
                  a: {
                    color: "#999",
                    lineHeight: 22,
                    align: "center"
                  },
                  hr: {
                    borderColor: "#aaa",
                    width: "100%",
                    borderWidth: 0.5,
                    height: 0
                  },
                  b: {
                    fontSize: 16,
                    lineHeight: 33
                  },
                  per: {
                    color: "#eee",
                    backgroundColor: "#334455",
                    padding: [2, 4],
                    borderRadius: 2
                  }
                }
              }
            },
            data: []
          }
        ]
      }
    };
  },
  components: {
    Schart
  },
  computed: {
    role() {
      return this.name === "admin" ? "超级管理员" : "普通用户";
    }
  },
  created() {
    this.handleListener();
    this.changeDate();
    getOrderList()
      .then(result => {
        this.showAddress(result);
        this.showMoney(result);
        this.showPayMethod(result);
        this.$nextTick(() => {
          this.showEcharts();
        });
      })
      .catch(e => console.log(e));
  },
  activated() {
    this.handleListener();
  },
  deactivated() {
    window.removeEventListener("resize", this.renderChart);
    bus.$off("collapse", this.handleBus);
  },
  methods: {
    showPayMethod(data) {
      const obj = {};
      data.map(item => {
        // console.log(item.payInfo.method)
        if (obj[item.payInfo.method]) {
          obj[item.payInfo.method]++;
        } else {
          obj[item.payInfo.method] = 1;
        }
      });
      // console.log(obj)
      for (let prop in obj) {
        this.option3.legend.data.push(prop);
        this.option3.series[0].data.push({ value: obj[prop], name: prop });
        this.option3.series[1].data.push({ value: obj[prop], name: prop });
      }
    },
    showMoney(data) {
      const obj = {};
      data.map(item => {
        // console.log(item.time.split('-')[1], item.payInfo.money)
        if (obj[item.time.split("-")[1]]) {
          obj[item.time.split("-")[1]] += item.payInfo.money;
        } else {
          obj[item.time.split("-")[1]] = item.payInfo.money;
        }
      });
      for (let prop in obj) {
        this.data.push({ name: prop, value: obj[prop] });
      }
      this.data.sort(this.compareMon("name"));
    },
    compareMon(prop) {
      // 按照属性排序
      return (obj1, obj2) => {
        let val1 = obj1[prop];
        let val2 = obj2[prop];
        if (val1 < val2) {
          return -1;
        } else if (val1 > val2) {
          return 1;
        } else {
          return 0;
        }
      };
    },
    showAddress(data) {
      const obj = {};
      data.map(item => {
        if (obj[item.userInfo.address]) {
          obj[item.userInfo.address]++;
        } else {
          obj[item.userInfo.address] = 1;
        }
      });
      for (let prop in obj) {
        this.address.push({
          address: prop,
          count: obj[prop],
          precent: Math.floor((obj[prop] / data.length) * 100)
        });
      }
      // console.log(this.address)
    },
    showEcharts() {
      this.Echarts = echarts.init(document.getElementById("pieChart"));
      this.Echarts.setOption(this.option3);
    },
    changeDate() {
      const now = new Date().getTime();
      this.data.forEach((item, index) => {
        const date = new Date(now - (6 - index) * 86400000);
        item.name = `${date.getFullYear()}/${date.getMonth() +
          1}/${date.getDate()}`;
      });
    },
    handleListener() {
      bus.$on("collapse", this.handleBus);
      // 调用renderChart方法对图表进行重新渲染
      window.addEventListener("resize", this.renderChart);
    },
    handleBus(msg) {
      setTimeout(() => {
        this.renderChart();
      }, 300);
    },
    renderChart() {
      // this.$refs.bar.renderChart();
      this.$refs.line.renderChart();
    }
  },
  mounted() {
    // this.showEcharts()
  }
};
</script>

<style scoped>
.el-row {
  margin-bottom: 20px;
}

.grid-content {
  display: flex;
  align-items: center;
  height: 100px;
}

.grid-cont-right {
  flex: 1;
  text-align: center;
  font-size: 14px;
  color: #999;
}

.grid-num {
  font-size: 30px;
  font-weight: bold;
}

.grid-con-icon {
  font-size: 50px;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
  color: #fff;
}

.grid-con-1 .grid-con-icon {
  background: rgb(45, 140, 240);
}

.grid-con-1 .grid-num {
  color: rgb(45, 140, 240);
}

.grid-con-2 .grid-con-icon {
  background: rgb(100, 213, 114);
}

.grid-con-2 .grid-num {
  color: rgb(45, 140, 240);
}

.grid-con-3 .grid-con-icon {
  background: rgb(242, 94, 67);
}

.grid-con-3 .grid-num {
  color: rgb(242, 94, 67);
}

.user-info {
  display: flex;
  align-items: center;
  padding-bottom: 20px;
  border-bottom: 2px solid #ccc;
  margin-bottom: 20px;
}

.user-avator {
  width: 120px;
  height: 120px;
  border-radius: 50%;
}

.user-info-cont {
  padding-left: 50px;
  flex: 1;
  font-size: 14px;
  color: #999;
}

.user-info-cont div:first-child {
  font-size: 30px;
  color: #222;
}

.user-info-list {
  font-size: 14px;
  color: #999;
  line-height: 25px;
}

.user-info-list span {
  margin-left: 70px;
}

.mgb20 {
  margin-bottom: 20px;
}

.todo-item {
  font-size: 14px;
}

.todo-item-del {
  text-decoration: line-through;
  color: #999;
}

.schart {
  width: 100%;
  height: 300px;
}
</style>
